package com.sk.rpcAssist.io.socket;



import com.sk.rpcAssist.domain.BasicConfig;
import com.sk.rpcAssist.domain.ProvideInfoValue;
import com.sk.rpcAssist.io.protocol.MessageProtocolInter;
import com.sk.rpcAssist.io.protocol.RpcResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.Socket;

/**
 * description：
 *
 * @author 孙文斌
 * @Date: 2021/1/27 9:24
 */
@Slf4j
public class ClientSocket {

    public static Object invoke(ProvideInfoValue provideInfo, MessageProtocolInter messageProtocol) {
        Socket socket = null;
        try {
            socket = new Socket(provideInfo.getIp(), provideInfo.getPort());
            OutputStream outputStream = socket.getOutputStream();
            InputStream inputStream = socket.getInputStream();
            messageProtocol.clientToRequest(provideInfo.getRpcRequest(),outputStream);
            RpcResponse rpcResponse = messageProtocol.clientGetResponse(inputStream);
            return rpcResponse;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("socket operation fail,exception info :" + e);
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    log.error("socket close exception,exception info :" + e);
                }
            }
        }
        return null;
    }
}
